package cn.luyifushi.config.security.handler;

import cn.luyifushi.config.redis.service.RedisService;
import cn.luyifushi.utils.JwtUtils;
import cn.luyifushi.utils.LoginResult;
import cn.luyifushi.utils.Result;
import cn.luyifushi.utils.ResultCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import cn.luyifushi.sys.entity.User;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sword-l
 * @version 1.0.0
 * @title 登录认证成功处理器类
 * @description
 **/
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {
        //设置客户端的响应的内容类型
        response.setContentType("application/json;charset=UTF-8");
        //获取当登录用户信息
        User user = (User) authentication.getPrincipal();
        //生成token
        String token = jwtUtils.generateToken(user);
        //设置token签名密钥及过期时间
        long expireTime = Jwts.parser() //获取DefaultJwtParser对象
                .setSigningKey(jwtUtils.getSecret()) //设置签名的密钥
                .build()
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();//获取token过期时间

        Map<String,Object> loginResult = new HashMap<String,Object>(2){{
            put("uid", user.getId());
            put("token", token);
            put("expireTime",expireTime);
        }};
        //消除循环引用
        String result = JSON.toJSONString(Result.ok(loginResult).code(ResultCode.SUCCESS), SerializerFeature.DisableCircularReferenceDetect);
        //将token信息保存到redis中
        String tokenKey="token_"+token;
        redisService.set(tokenKey,token,jwtUtils.getExpiration()/1000);
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
